/**
 * Copyright 2015 Software innovation and R & D center. All rights reserved.
 * File Name: AES128Utils.java
 * Encoding UTF-8
 * Version: 0.0.1
 * History:	2015年1月15日
 */
package net.huashitong.ssydt.provider.utils.encrypt;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;


/**
 * AES128加密工具
 * @author: weihuang.peng
 * @version Revision: 0.0.1
 * @Date: 2015年1月15日
 */
public class AES128Utils {

	public static final int keyBit = 128;
	
	private static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1)
			return null;
		byte[] result = new byte[hexStr.length() / 2];
		for (int i = 0; i < hexStr.length() / 2; i++) {
			int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
			result[i] = (byte) (high * 16 + low);
		}
		return result;
	}

	private static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	private static byte[] decrypt(byte[] content, String password)
			throws Exception {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		kgen.init(keyBit, new SecureRandom(password.getBytes()));
		SecretKey secretKey = kgen.generateKey();
		byte[] enCodeFormat = secretKey.getEncoded();
		SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.DECRYPT_MODE, key);
		byte[] result = cipher.doFinal(content);
		return result;
	}

	private static byte[] encrypt(String content, String password)
			throws Exception {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		kgen.init(keyBit, new SecureRandom(password.getBytes()));
		SecretKey secretKey = kgen.generateKey();
		byte[] enCodeFormat = secretKey.getEncoded();
		SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
		Cipher cipher = Cipher.getInstance("AES");
		byte[] byteContent = content.getBytes("utf-8");
		cipher.init(Cipher.ENCRYPT_MODE, key);
		byte[] result = cipher.doFinal(byteContent);
		return result;
	}

	/**
	 * 加密方法
	 * @param content 加密内容
	 * @param password 密钥
	 * @return
	 * @throws Exception
	 */
	public static String Encrypt(String content, String password)
			throws Exception {
		return parseByte2HexStr(encrypt(content, password));
	}

	/**
	 * 解密方法
	 * @param content 密文
	 * @param password 密钥
	 * @return
	 * @throws Exception
	 */
	public static String Decrypt(String content, String password)
			throws Exception {
		return new String(decrypt(parseHexStr2Byte(content), password));
	}
}
